package com.dbq.fast.business.coupons;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.dbq.fast.R;
import com.dbq.fast.business.coupons.bean.ContentBean;
import com.dbq.fast.business.product.ui.StatusView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 */

/**
 * TODO  暂时先不处理加载更多
 */
@SuppressLint("ValidFragment")
public class CouponsFragment extends Fragment {

    private static CouponsFragment f;

    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.status_view)
    StatusView statusView;


    private int index;

    private CouponsAdapter adapter = null;
    private List<ContentBean>  data;
    private List<ContentBean>  cacheData = new ArrayList<>();

    public static int LOAD_MORE = 006;
    public static int REFRESH = 007;
    public static int NET_SURE = 001;
    public static int NET_ERROR = 0;
    private int cacheRefreshStatus = REFRESH;

    @SuppressLint("ValidFragment")
    public CouponsFragment(){
    }

    public static CouponsFragment newInstance(int index){
        f =  new CouponsFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

    public  void notifyData(List<ContentBean> t,int REFRESH_STATUS,int NET_STATUS){
        /**
         * 这里缓存数据的目的：解决加载数据的接口处理时长小于ui渲染的时长。提前调用了notifyData()方法。
         */
        this.cacheData = t;
        this.cacheRefreshStatus = REFRESH_STATUS;
        if (swipeRefreshLayout!= null && swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        if (REFRESH_STATUS == LOAD_MORE){//加载更多就直接添加到集合
            if (data != null){
                data.addAll(t);
            }
        }else if (REFRESH_STATUS == REFRESH){//刷新就清除数据，再添加到集合
            if (data!=null){
                data.clear();
                if (t != null)
                    data.addAll(t);
            }
        }
        if (adapter!=null){
            adapter.notifyDataSetChanged();
        }
        if (NET_STATUS == NET_ERROR){
            updateStatus(StatusView.NET_ERROR);
        }else if (t == null){//当传入的数据集合为空时，表示请求数据异常
            updateStatus(StatusView.SERVICE_ERROR);
        }else if ( data == null){
            updateStatus(StatusView.LOADING);
        }else if (data.isEmpty()){
            if (index == 0){
                updateStatus(StatusView.NO_COUPONS);
            }else if(index == 1){
                updateStatus(StatusView.NO_USED_COUPONS);
            }else{
                updateStatus(StatusView.NO_UNVALIED_COUPONS);
            }
        }else{
            updateStatus(StatusView.SUCCESS);
        }

    }
    public void updateStatus(int status){
        if (statusView!=null){
            statusView.setStatus(status);
        }
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View  rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_coupons_view,null);
        ButterKnife.bind(this,rootView);
        data = new ArrayList<>();

        index = getArguments().getInt("index");
        adapter = new CouponsAdapter(getContext(),data);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        updateStatus(StatusView.LOADING);
        statusView.setRefreshListener(() -> {
            ((IOnRefreshCallback)getActivity()).onRefresh(REFRESH);
        });
        swipeRefreshLayout.setOnRefreshListener(() -> {
            ((IOnRefreshCallback)getActivity()).onRefresh(REFRESH);
        });
//        notifyData(cacheData,cacheRefreshStatus,NET_SURE);
        return rootView;
    }

    private class CouponsAdapter extends RecyclerView.Adapter{

        private  List<ContentBean> list;
        private LayoutInflater inflater;

        public CouponsAdapter(Context context, List<ContentBean> list){
            this.list = list;
            inflater = LayoutInflater.from(context);
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View rootView = inflater.inflate(R.layout.adapter_coupons_item_view,null);
                return new CouponsHolder(rootView);
        }

        @Override
        public int getItemViewType(int position) {

            return list.get(position).discount.discountType;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if(holder instanceof CouponsHolder){
                CouponsHolder h = (CouponsHolder) holder;
                Resources resources = holder.itemView.getContext().getResources();
                ContentBean cb =  data.get(position);
                if (cb.discount.discountType == 1){ //新人卡券
                    h.discountAmout.setText(cb.discount.discountAmount+"折");
                    h.couponsTitle.setText(cb.discount.discountName);
                    h.discountExpire.setText(String.format("限%s个月套餐使用",getChinesChar(cb.discount.discountSetmealTime)));
                    h.validTime.setText(String.format("有效期至%s",getValidTime(cb.discountExpired)));
                    if (index == 0){
                        h.leftTime.setVisibility(View.VISIBLE);
                        h.leftTime.setText(getLeftTime(cb.timeRemain));
                    }else {
                        h.leftTime.setVisibility(View.GONE);
                    }

                    if (index == 0){//第一页有不同的颜色
                        h.discountAmout.setTextColor(resources.getColor(R.color.coupons_color));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.coupons_black));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.coupons_color));
                    }else{ //未使用和已过期的界面都显示为灰色
                        h.discountAmout.setTextColor(resources.getColor(R.color.font_normal));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.font_normal));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.font_normal));
                    }
                }else if(cb.discount.discountType == 2){ // 分享卡券
                    h.discountAmout.setText(cb.discount.discountAmount+"天");
                    h.couponsTitle.setText(cb.discount.discountName);
                    h.discountExpire.setVisibility(View.INVISIBLE);
                    h.validTime.setText(String.format("生效时间:%s",getValidTime(cb.discountExpired)));
                    h.typeName.setText(cb.discount.discountSlogan);
                    if (index == 0){
                        h.leftTime.setVisibility(View.VISIBLE);
                        h.leftTime.setText(getLeftTime(cb.timeRemain));
                    }else {
                        h.leftTime.setVisibility(View.GONE);
                    }

                    if (index == 0){//第一页有不同的颜色
                        h.discountAmout.setTextColor(resources.getColor(R.color.coupons_color));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.coupons_black));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.coupons_color));
                    }else{ //未使用和已过期的界面都显示为灰色
                        h.discountAmout.setTextColor(resources.getColor(R.color.font_normal));
                        h.couponsTitle.setTextColor(resources.getColor(R.color.font_normal));
                        h.discountExpire.setTextColor(resources.getColor(R.color.font_normal));
                        h.validTime.setTextColor(resources.getColor(R.color.font_normal));
                        h.leftTime.setTextColor(resources.getColor(R.color.font_normal));
                    }
                }

            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        private String getValidTime(long discountExpired){
            Date d = new Date(discountExpired);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(d);
        }
        private String getLeftTime(long timeRemain){
            if (timeRemain < 0){
                return "已过期";
            }else if (timeRemain < 24 * 60 * 60 * 1000){
                return "不足1天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 2){
                return "不足2天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 3){
                return "不足3天";
            }else if (timeRemain < 24 * 60 * 60 * 1000 * 4){
                return "不足4天";
            }
            return "";
        }
        /**
         * 将返回的月份转换为中文
         * @param mouth
         * @return
         */
        private String getChinesChar(int mouth){
            String t = "一";
            if (mouth == 1){
                t = "一";
            }else if(mouth == 3){
                t = "三";
            }else if(mouth == 6){
                t = "六";
            }else if(mouth == 12){
                t = "十二";
            }
            return t;
        }
    }


    public class CouponsHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.discount_amount)
        TextView discountAmout;

        @BindView(R.id.coupons_title)
        TextView couponsTitle;

        @BindView(R.id.discount_expire)
        TextView discountExpire;

        @BindView(R.id.valid_time)
        TextView validTime;

        @BindView(R.id.left_time)
        TextView leftTime;//剩余时间

        @BindView(R.id.type_name)
        TextView typeName;
        public CouponsHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }

}
